package com.moli.handler.security;

import com.alibaba.fastjson.JSON;
import com.moli.domain.ResponseResult;
import com.moli.enums.AppHttpCodeEnum;
import com.moli.utils.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author： XC
 * @Date： 2023-06-08 08:59
 * @Description： 认证失败处理器
 */

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
		//打印异常信息
		authException.printStackTrace();
		//InsufficientAuthenticationException
		//BadCredentialsException
		ResponseResult result = null;
		//用户名或密码错误所返回的异常
		if (authException instanceof BadCredentialsException) {
			result = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR.getCode(), authException.getMessage());
		}
		//权限不足或未登录所返回的异常
		else if (authException instanceof InsufficientAuthenticationException) {
			//未登录
			result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
		} else {
			//权限不足
			result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(), "认证或授权失败");
		}
		//响应给前端
		WebUtils.renderString(response, JSON.toJSONString(result));
	}
}